import { Hono } from 'hono';
import { AppDataSource, checkDatabaseHealth } from '@weubi/shared';

export const healthRoutes = new Hono();

// 基础健康检查
healthRoutes.get('/', async (c) => {
  const startTime = Date.now();
  
  try {
    // 检查数据库连接
    const dbHealthy = await checkDatabaseHealth();
    
    // 检查内存使用
    const memoryUsage = process.memoryUsage();
    
    // 检查运行时间
    const uptime = process.uptime();
    
    const responseTime = Date.now() - startTime;
    
    const health = {
      status: dbHealthy ? 'healthy' : 'unhealthy',
      timestamp: new Date().toISOString(),
      uptime: Math.floor(uptime),
      responseTime,
      version: process.env.npm_package_version || '1.0.0',
      environment: process.env.NODE_ENV || 'development',
      services: {
        database: {
          status: dbHealthy ? 'up' : 'down',
          connected: AppDataSource.isInitialized,
        },
        memory: {
          rss: Math.round(memoryUsage.rss / 1024 / 1024),
          heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024),
          heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024),
          external: Math.round(memoryUsage.external / 1024 / 1024),
        },
      },
    };
    
    return c.json(health, dbHealthy ? 200 : 503);
  } catch (error) {
    return c.json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: error instanceof Error ? error.message : 'Unknown error',
      responseTime: Date.now() - startTime,
    }, 500);
  }
});

// 详细健康检查
healthRoutes.get('/detailed', async (c) => {
  const startTime = Date.now();
  
  try {
    // 数据库检查
    const dbHealthy = await checkDatabaseHealth();
    let dbStats = null;
    
    if (dbHealthy) {
      try {
        const result = await AppDataSource.query(`
          SELECT 
            schemaname,
            tablename,
            n_tup_ins as inserts,
            n_tup_upd as updates,
            n_tup_del as deletes
          FROM pg_stat_user_tables
          ORDER BY schemaname, tablename
        `);
        dbStats = result;
      } catch (err) {
        console.warn('Could not fetch database stats:', err);
      }
    }
    
    // 系统信息
    const systemInfo = {
      platform: process.platform,
      arch: process.arch,
      nodeVersion: process.version,
      pid: process.pid,
      uptime: process.uptime(),
      cpuUsage: process.cpuUsage(),
      memoryUsage: process.memoryUsage(),
    };
    
    const health = {
      status: dbHealthy ? 'healthy' : 'unhealthy',
      timestamp: new Date().toISOString(),
      responseTime: Date.now() - startTime,
      system: systemInfo,
      services: {
        database: {
          status: dbHealthy ? 'up' : 'down',
          connected: AppDataSource.isInitialized,
          stats: dbStats,
        },
      },
    };
    
    return c.json(health, dbHealthy ? 200 : 503);
  } catch (error) {
    return c.json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: error instanceof Error ? error.message : 'Unknown error',
      responseTime: Date.now() - startTime,
    }, 500);
  }
});

// 就绪检查（用于 Kubernetes 等）
healthRoutes.get('/ready', async (c) => {
  try {
    const dbHealthy = await checkDatabaseHealth();
    
    if (dbHealthy) {
      return c.json({
        status: 'ready',
        timestamp: new Date().toISOString(),
      });
    } else {
      return c.json({
        status: 'not ready',
        reason: 'Database not available',
        timestamp: new Date().toISOString(),
      }, 503);
    }
  } catch (error) {
    return c.json({
      status: 'not ready',
      reason: error instanceof Error ? error.message : 'Unknown error',
      timestamp: new Date().toISOString(),
    }, 503);
  }
});

// 存活检查（用于 Kubernetes 等）
healthRoutes.get('/live', (c) => {
  return c.json({
    status: 'alive',
    timestamp: new Date().toISOString(),
  });
});
